﻿// ———————————————————————–
// <copyright file="MGRSCoordinate.cs" company="The MITRE Corporation">
//    Copyright (c) 2014 The MITRE Corporation. All rights reserved.
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>
// ———————————————————————–
/////////////////////////////////////////////////////////////////////////////////////////////////
// MGRSCoordinate.cs:
//
// A coordinate from the Military Grid Reference System (MGRS) which represents a location using the Universal Transverse Mercator (UTM) and the UPS grid systems and a unique military grid labeling convention.
//
// Project: IC.NET - CAD Library
// Author:  Jim Cronin - MITRE
/////////////////////////////////////////////////////////////////////////////////////////////////

// Copyright (c) 2014 The MITRE Corporation. All rights reserved.
//
// NOTICE
// This software was produced for the U. S. Government
// under Contract No. FA8721-09-C-0001, and is
// subject to the Rights in Noncommercial Computer Software
// and Noncommercial Computer Software Documentation Clause
// (DFARS) 252.227-7014 (JUN 1995)

using System;
using System.Text.RegularExpressions;
using System.Xml;

namespace EDXLSharp.NIEMCore
{
  /// <summary>
  /// A coordinate from the Military Grid Reference System (MGRS) which represents a location using the Universal Transverse Mercator (UTM) and the UPS grid systems and a unique military grid labeling convention.
  /// </summary>
  public class MGRSCoordinate : IComposable
  {
    //TODO: MGRSCoordinate - Not going to fully expand into ComplexTypeBase implementation at this time - will do later as needed

    private static string ValidGridZoneIdPattern = "^[0-9][0-9]?[A-Za-z]$"; //One or two digits followed by a letter
    private static string ValidGridZoneSquareIdPattern = "^([A-Za-z]{2})?$"; //Two letters or blank

    /// <summary>
    /// An identifier of a Military Grid Reference System (MGRS) coordinate.
    /// </summary>
    public string Id { get; set; }

    /// <summary>
    /// A distance east within a MGRS zone.
    /// </summary>
    public int EastingValue { get; set; }

    /// <summary>
    /// A distance north within a MGRS zone.
    /// </summary>
    public int NorthingValue { get; set; }

    /// <summary>
    /// A spatial reference system.
    /// </summary>
    public GeographicDatumText GeographicDatum { get; set; }

    /// <summary>
    /// An identifier of a MGRS grid zone.
    /// </summary>
    public string GridZoneId { get; set; }

    /// <summary>
    /// An identifier of a specific 100,000 meter squared region within a MGRS grid zone.
    /// </summary>
    public string GridZoneSquareId { get; set; }

    /// <summary>
    /// Writes this Object to an inline XML Document
    /// </summary>
    /// <param name="xwriter">Valid XMLWriter</param>
    /// <exception cref="System.ArgumentNullException">Thrown if xwriter is null</exception>
    /// <exception cref="EDXLSharp.ValidationException">Thrown if the object fails to validate</exception>
    public void WriteXML(XmlWriter xwriter)
    {
      if (xwriter == null)
      {
        throw new ArgumentNullException("xwriter");
      }

      this.Validate();

      xwriter.WriteStartElement("MGRSCoordinate", EDXLConstants.NiemCoreNamespace);
      xwriter.WriteElementString("MGRSCoordinateID", EDXLConstants.NiemCoreNamespace, this.Id);
      xwriter.WriteElementString("MGRSEastingValue", EDXLConstants.NiemCoreNamespace, this.EastingValue.ToString());
      xwriter.WriteElementString("MGRSNorthingValue", EDXLConstants.NiemCoreNamespace, this.NorthingValue.ToString());
      GeographicDatum.WriteXML(xwriter);
      xwriter.WriteElementString("MGRSGridZoneID", EDXLConstants.NiemCoreNamespace, this.GridZoneId);
      xwriter.WriteElementString("MGRSGridZoneSquareID", EDXLConstants.NiemCoreNamespace, this.GridZoneSquareId);
      xwriter.WriteEndElement();
    }

    /// <summary>
    /// Reads this Object's values from an XML nodelist
    /// </summary>
    /// <param name="rootnode">root XML Node of the Object element</param>
    /// <exception cref="System.ArgumentNullException">Thrown if rootnode is null</exception>
    /// <exception cref="System.ArgumentException">Thrown if the rootnode is not the correct type</exception>
    /// <exception cref="EDXLSharp.ValidationException">Thrown if the object fails to validate</exception>
    public void ReadXML(XmlNode rootnode)
    {
      if (rootnode == null)
      {
        throw new ArgumentNullException("rootnode");
      }
      if (rootnode.LocalName != "MGRSCoordinate")
      {
        throw new ArgumentException("Unexpected element " + rootnode.LocalName + " instead of MGRSCoordinate");
      }

      foreach (XmlNode node in rootnode.ChildNodes)
      {
        switch (node.LocalName)
        {
          case "MGRSCoordinateID":
            this.Id = node.InnerText;
            break;
          case "MGRSEastingValue":
            int eval;
            if (!int.TryParse(node.InnerText, out eval))
            {
              throw new ValidationException("Easting Value must be a non-negative integer");
            }
            this.EastingValue = eval;
            break;
          case "MGRSNorthingValue":
            int nval;
            if (!int.TryParse(node.InnerText, out nval))
            {
              throw new ValidationException("Northing Value must be a non-negative integer");
            }
            this.NorthingValue = nval;
            break;
          case "GeographicDatumText":
            GeographicDatum = new GeographicDatumText();
            GeographicDatum.ReadXML(node);
            break;
          case "MGRSGridZoneID":
            this.GridZoneId = node.InnerText;
            break;
          case "MGRSGridZoneSquareID":
            this.GridZoneSquareId = node.InnerText;
            break;
          default:
            throw new ArgumentException("Unexpected element " + node.LocalName + " in MGRSCoordinate");
        }
      }

      this.Validate();
    }

    /// <summary>
    /// Validates This Message element For Required Values and Conformance
    /// </summary>
    /// <exception cref="EDXLSharp.ValidationException">Thrown if the object fails to validate</exception>
    public void Validate()
    {
      if (string.IsNullOrEmpty(Id))//TODO: MGRSCoorindate.Validate - valid/invalid values for ID?
      {
        throw new ValidationException("Missing required field CoordinateId");
      }
      if (EastingValue < 0)
      {
        throw new ValidationException("Easting Value must be a non-negative integer");
      }
      if (NorthingValue < 0)
      {
        throw new ValidationException("Northing Value must be a non-negative integer");
      }
      if (GeographicDatum == null)
      {
        throw new ValidationException("Missing required element GeographicDatumText");
      }
      GeographicDatum.Validate();
      if (string.IsNullOrEmpty(GridZoneId))
      {
        throw new ValidationException("Missing required field GridZoneId");
      }
      if(!Regex.IsMatch(GridZoneId, ValidGridZoneIdPattern))
      {
        throw new ValidationException("Invalid GridZoneId: " + GridZoneId);
      }
      if (GridZoneSquareId == null)
      {
        throw new ValidationException("Missing required field GridZoneSquareId");
      }
      if (!Regex.IsMatch(GridZoneSquareId, ValidGridZoneSquareIdPattern))
      {
        throw new ValidationException("Invalid GridZoneSquareId: " + GridZoneSquareId);
      }
    }
  }
}